import type { DirectiveBinding } from 'vue'
import useUserStore from '@/stores/user'
import { hasPermission } from '@/utils/common'

// 页面元素权限  按钮权限
function checkPermission(el: HTMLElement, binding: DirectiveBinding) {
  const { value } = binding
  const userStore = useUserStore()
  const roles = userStore.userInfo.roles

  if (Array.isArray(value)) {
    if (value.length > 0) {
      const permissionValue = value
      const permission = hasPermission(permissionValue, roles)
      if (!permission && el.parentElement) {
        el.parentNode?.removeChild(el)
      }
    }
  } else {
    // eslint-disable-next-line quotes
    throw new Error(`need roles! Like v-permission="['admin','user']"`)
  }
}

export default {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    checkPermission(el, binding)
  },
  updated(el: HTMLElement, binding: DirectiveBinding) {
    checkPermission(el, binding)
  }
}
